package com.sayimo.maker.user.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.sayimo.framework.common.util.VerifyCodeUtil;
import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.base.dao.BaseConfigDao;
import com.sayimo.maker.base.service.UploadFileService;
import com.sayimo.maker.commons.Constant;
import com.sayimo.maker.commons.GeneratorUtils;
import com.sayimo.maker.commons.ali.pay.ALiPay;
import com.sayimo.maker.commons.ali.pay.ALiTransfer;
import com.sayimo.maker.commons.ali.pay.AliScancodePay;
import com.sayimo.maker.commons.ali.pay.AliWapPay;
import com.sayimo.maker.commons.push.Demo;
import com.sayimo.maker.commons.utils.Base64Utils;
import com.sayimo.maker.commons.utils.CbcEncrypt;
import com.sayimo.maker.commons.utils.DES3;
import com.sayimo.maker.commons.utils.JSONUtil;
import com.sayimo.maker.commons.utils.MD5Util;
import com.sayimo.maker.commons.utils.MatrixToImageWriter;
import com.sayimo.maker.commons.utils.PropertiesUtils;
import com.sayimo.maker.commons.utils.RedisUtils;
import com.sayimo.maker.commons.utils.RequestUtils;
import com.sayimo.maker.commons.wx.pay.WXPay;
import com.sayimo.maker.commons.wx.pay.WXScanCodePay;
import com.sayimo.maker.user.dao.CustomerInterfaceDao;
import com.sayimo.maker.user.dao.CustomerShareInterfaceDao;
import com.sayimo.maker.user.dao.EnterpriseInfoDao;
import com.sayimo.maker.user.dao.EnterpriseWalletIncomeExpendRecordInterfaceDao;
import com.sayimo.maker.user.dao.EnterpriseWalletInterfaceDao;
import com.sayimo.maker.user.dao.MemberActiveInterfaceDao;
import com.sayimo.maker.user.dao.MemberCustomerInterfaceDao;
import com.sayimo.maker.user.dao.ReceivingAddressInterfaceDao;
import com.sayimo.maker.user.dao.WalletIncomeExpendRecordInterfaceDao;
import com.sayimo.maker.user.dao.WalletInterfaceDao;
import com.sayimo.maker.user.service.CustomerInterfaceService;
import com.sayimo.maker.user.service.CustomerShareInterfaceService;
import com.sayimo.maker.user.service.SmsVerifyCodeInterfaceService;
import com.sayimo.maker.user.service.WalletIncomeExpendRecordService;
import com.sayimo.maker.user.service.WalletInterfaceService;
import com.sayimo.maker.user.vo.Customer;
import com.sayimo.maker.user.vo.EnterpriseInfo;
import com.sayimo.maker.user.vo.EnterpriseWallet;
import com.sayimo.maker.user.vo.EnterpriseWalletIncomeExpendRecord;
import com.sayimo.maker.user.vo.SmsVerifyCode;
import com.sayimo.maker.user.vo.Wallet;
import com.sayimo.maker.user.vo.WalletIncomeExpendRecord;
import com.sayimo.uploadfile.util.UploadFileInfo;
import com.sayimo.uploadfile.util.UploadFileResult;

import sun.misc.BASE64Encoder;

/**
 * @Copyright (c) 2015 广东省尚一互联网有限公司
 * @Project: schoolmallapi
 * @ClassName: CustomerIterfaceImplService
 * @Description:
 * @Author: chenpy
 * @Date: 日期：2015年12月24日 时间：下午2:04:57
 * @Version 1.0.0
 */
@SuppressWarnings("restriction")
@Service("customerInterfaceImplService")
public class CustomerInterfaceImplService implements CustomerInterfaceService {

	private static Log logger = LogFactory.getLog(CustomerInterfaceImplService.class);

	@Autowired
	private CustomerInterfaceDao customerInterfaceImplDao;

	@Autowired
	private CustomerShareInterfaceService customerShareInterfaceImplService;
	@Resource(name = "transactionManager")
	private DataSourceTransactionManager transactionManager;
	@Autowired
	private SmsVerifyCodeInterfaceService smsVerifyCodeInterfaceImplService;
	@Resource(name = "walletInterfaceDao")
	private WalletInterfaceDao walletInterfaceDao;
	@Resource(name = "activeInterfaceImplDao")
	private MemberActiveInterfaceDao activeInterfaceDao;
	@Resource(name = "memberCustomerInterfaceDao")
	private MemberCustomerInterfaceDao memberCustomerInterfaceDao;
	@Resource(name = "enterpriseInfoDao")
	private EnterpriseInfoDao enterpriseInfoDao;
	@Autowired(required = false)
	private HttpServletRequest request;
	@Resource(name = "customerShareInterfaceImplDao")
	private CustomerShareInterfaceDao customerShareInterfaceImplDao;
	@Resource(name = "receivingAddressInterfaceImplDao")
	private ReceivingAddressInterfaceDao receivingAddressInterfaceImplDao;
	@Resource(name = "walletInterfaceService")
	private WalletInterfaceService walletInterfaceImplService;
	@Resource(name = "walletIncomeExpendRecordInterfaceDao")
	private WalletIncomeExpendRecordInterfaceDao walletIncomeExpendRecordInterfaceDao;
	@Resource(name = "uploadFileService")
	private UploadFileService uploadFileService;
	@Resource(name = "baseConfigDao")
	private BaseConfigDao baseConfigDao;
	@Resource(name = "walletIncomeExpendRecordServiceImpl")
	private WalletIncomeExpendRecordService walletIncomeExpendRecordServiceImpl;
	@Resource(name = "enterpriseWalletInterfaceDao")
	private EnterpriseWalletInterfaceDao enterpriseWalletInterfaceDao;
	@Resource(name = "enterpriseWalletIncomeExpendRecordInterfaceDao")
	private EnterpriseWalletIncomeExpendRecordInterfaceDao enterpriseWalletIncomeExpendRecordInterfaceDao;

	public CustomerInterfaceDao getCustomerInterfaceImplDao() {
		return customerInterfaceImplDao;
	}

	public void setCustomerInterfaceImplDao(CustomerInterfaceDao customerInterfaceImplDao) {
		this.customerInterfaceImplDao = customerInterfaceImplDao;
	}

	public CustomerShareInterfaceService getCustomerShareInterfaceImplService() {
		return customerShareInterfaceImplService;
	}

	public void setCustomerShareInterfaceImplService(CustomerShareInterfaceService customerShareInterfaceImplService) {
		this.customerShareInterfaceImplService = customerShareInterfaceImplService;
	}

	public SmsVerifyCodeInterfaceService getSmsVerifyCodeInterfaceImplService() {
		return smsVerifyCodeInterfaceImplService;
	}

	public void setSmsVerifyCodeInterfaceImplService(SmsVerifyCodeInterfaceService smsVerifyCodeInterfaceImplService) {
		this.smsVerifyCodeInterfaceImplService = smsVerifyCodeInterfaceImplService;
	}

	/**
	 * 
	 * @Title: getUserInfo
	 * @Author: 田超
	 * @Date:日期：2017年2月15日 : 上午9:55:17
	 * @Description:个人中心首页,用户信息
	 * @return Map<String,Object>
	 * @Version 1.0.0
	 */
	public Map<String, Object> getUserInfo(String accout) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Customer customer = customerInterfaceImplDao.queryCustomerInfo(accout);
			Wallet wallet = walletInterfaceDao.queryWalletByCustomerId(customer.getId());
			Map<String, Object> map = customerInterfaceImplDao.queryCustomerCount(customer.getId());
			Map<String, Object> enterpriseMap = new HashMap<String, Object>();
			if (customer.getProviderRefId() != null) {
				enterpriseMap = enterpriseInfoDao.queryCustomerStatu(customer.getProviderRefId());
			}
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("accout", customer.getAccout());
			dataMap.put("alias", customer.getAlias());
			dataMap.put("headphoto", customer.getHeadPhoto());

			if (customer.getMakerLevel() == null) {
				dataMap.put("makerlevel", 0);
			} else {
				dataMap.put("makerlevel", customer.getMakerLevel());
			}
			if (enterpriseMap != null && enterpriseMap.get("providerType") != null
					&& enterpriseMap.get("status") != null) {
				dataMap.put("providertype", enterpriseMap.get("providerType"));
				dataMap.put("status", enterpriseMap.get("status"));
			} else {
				dataMap.put("providertype", null);
				dataMap.put("status", null);
			}
			dataMap.put("remainingsilverscore", wallet.getRemainingSilverScore());
			dataMap.put("mycustomer", map.get("num"));
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, dataMap);
		} catch (Exception e) {
			logger.info(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * 
	 * @Title: getUserInfo
	 * @Author: 田超
	 * @Date:日期：2017年2月15日 : 上午9:55:17
	 * @Description:个人中心,个人资料
	 * @return Map<String,Object>
	 * @Version 1.0.0
	 */
	public Map<String, Object> getUserDetail(String accout) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Customer customer = customerInterfaceImplDao.queryCustomerInfo(accout);
			Wallet wallet = walletInterfaceDao.queryWalletByCustomerId(customer.getId());
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("id", customer.getId());
			dataMap.put("accout", customer.getAccout());
			dataMap.put("alias", customer.getAlias());
			dataMap.put("headphoto", customer.getHeadPhoto());
			dataMap.put("realname", customer.getRealName());
			dataMap.put("sex", customer.getSex());
			dataMap.put("mobilephone", customer.getMobilePhone());
			dataMap.put("bankcodeno", wallet.getBankCodeNo());
			dataMap.put("bindType", wallet.getBindType());
			dataMap.put("peoplecode", customer.getPeopleCode());
			dataMap.put("bankBindUserName", wallet.getBankBindUserName());
			dataMap.put("bankBranchCode", wallet.getBankBranchCode());
			dataMap.put("bankBranchName", wallet.getBankBranchName());

			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, dataMap);
		} catch (DaoException e) {
			logger.info(e);
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * 
	 * @Title: updateCustomerInfo
	 * @Author: 田超
	 * @Date:日期：2017年2月17日 : 下午3:33:54
	 * @Description:更新用户信息
	 * @return Map<String,Object>
	 * @Version 1.0.0
	 */
	public Map<String, Object> updateCustomerInfo(HttpServletRequest request) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Customer customer = new Customer();
			Integer id = (Integer) request.getAttribute("customerId");
			customer.setId(id);
			customer.setAccout((String) request.getAttribute("accout"));
			customer.setAlias(request.getParameter("alias"));
			customer.setHeadPhoto(request.getParameter("headphoto"));
			customer.setRealName(request.getParameter("realname"));
			customer.setSex(request.getParameter("sex"));
			customer.setMobilePhone(request.getParameter("mobilephone"));
			customer.setPeopleCode(request.getParameter("peoplecode"));

			if (StringUtils.isNotBlank(request.getParameter("bankcodeno"))
					|| StringUtils.isNotBlank(request.getParameter("bankBindUserName"))) {
				Wallet wallet = new Wallet();
				if (StringUtils.isNotBlank(request.getParameter("bankcodeno"))) {
					wallet.setBankCodeNo(request.getParameter("bankcodeno"));
				}
				if (StringUtils.isNotBlank(request.getParameter("bankBindUserName"))) {
					wallet.setBankBindUserName(request.getParameter("bankBindUserName"));
				}
				Integer bindType = Integer.valueOf(request.getParameter("bindType"));
				wallet.setBindType(bindType);
				if(bindType==2){
					wallet.setBankBranchCode(request.getParameter("bankBranchCode"));
					wallet.setBankBranchName(request.getParameter("bankBranchName"));
				}

				wallet.setCustomerId(id);
				walletInterfaceDao.updateWallet(wallet);
			}

			customerInterfaceImplDao.updateCustomer(customer);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, Constant.SUCCESS);
		} catch (DaoException e) {
			logger.info(e);
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * @Title: getCustomerNum
	 * @Author: 田超
	 * @Date:日期：2017年2月16日 : 下午4:03:47
	 * @Description:会员管理
	 * @return Map<String,Object>
	 * @Version 1.0.0
	 */
	public Map<String, Object> getCustomerNum(String accout) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Customer customer = customerInterfaceImplDao.queryCustomerInfo(accout);
			List<Customer> list = customerInterfaceImplDao.queryProviderId(customer.getId());
			Map<String, Object> map = customerInterfaceImplDao.queryCustomerCount(customer.getId());
			List<Customer> childrenList = customerInterfaceImplDao.queryChilderCustomer(customer.getId());
			Integer provider = 0;
			Integer union = 0;
			for (Customer custom : list) {
				Map<String, Object> enterMap = enterpriseInfoDao.queryCustomerStatu(custom.getProviderRefId());
				if (enterMap != null && !enterMap.isEmpty()) {
					if (Integer.parseInt(String.valueOf(enterMap.get("providerType"))) == 1) {
						provider++;
					} else if (Integer.parseInt(String.valueOf(enterMap.get("providerType"))) == 2) {
						union++;
					}
				}
			}
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("num", map.get("num")); // 总会员
			if (map.get("goldnum") == null) {
				dataMap.put("goldnum", 0);
			} else {
				dataMap.put("goldnum", map.get("goldnum")); // 金会员
			}
			if (map.get("slivernum") == null) {
				dataMap.put("slivernum", 0); // 银会员
			} else {
				dataMap.put("slivernum", map.get("slivernum")); // 银会员
			}
			dataMap.put("provider", provider); // 供应商
			dataMap.put("union", union); // 联盟商
			if (map.get("goldnum") != null && map.get("slivernum") != null) {
				dataMap.put("makernum", Integer.parseInt(String.valueOf(map.get("goldnum")))
						+ Integer.parseInt(String.valueOf(map.get("slivernum")))); // 总创客
			} else if (map.get("goldnum") == null && map.get("slivernum") != null) {
				dataMap.put("makernum", Integer.parseInt(String.valueOf(map.get("slivernum")))); // 总创客
			} else if (map.get("goldnum") != null && map.get("slivernum") == null) {
				dataMap.put("makernum", Integer.parseInt(String.valueOf(map.get("goldnum")))); // 总创客
			} else {
				dataMap.put("makernum", 0); // 总创客
			}
			Map<String, Object> temMap = null;
			List tempList = new ArrayList();
			if (childrenList.size() > 0) {
				for (Customer custom : childrenList) {
					temMap = new HashMap<String, Object>();
					// temMap.put("accout",custom.getAccout());
					temMap.put("providertype", custom.getProviderType());
					temMap.put("providername", custom.getProviderName());
					temMap.put("makerLevel", custom.getMakerLevel());
					temMap.put("alias", custom.getAlias());
					temMap.put("createDate", custom.getCreateDate());
					tempList.add(temMap);
				}
			}
			dataMap.put("nextcustomernum", tempList);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, dataMap);
		} catch (Exception e) {
			logger.info(e);
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * @Package com.sayimo.rainbow.user.service.impl
	 * @Package com.sayimo.maker.user.service.impl
	 * @Author 龚益君
	 * @MethodName:inviteCodeNo
	 * @Description:生成邀请码
	 * @return
	 * @throws ServiceException
	 * @Date 2017年1月12日,上午11:37:42
	 */
	private String inviteCodeNo() throws ServiceException {
		String inviteCode = RandomStringUtils.random(4, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
		List<Customer> list;
		try {
			Customer customer = new Customer();
			customer.setInviteCode(inviteCode);
			list = customerInterfaceImplDao.queryCustomerByCond(customer);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
		if (list != null && !list.isEmpty()) {
			logger.info("inviteCode==" + inviteCode + "重复，需重新生成");
			inviteCodeNo();
		}
		return inviteCode;
	}

	public List<Customer> queryCustomerByCond(Customer customer) throws ServiceException {
		try {
			return customerInterfaceImplDao.queryCustomerByCond(customer);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/**
	 * @Title: queryAllLowerLevelMembers
	 * @Description:查询会员下对应的所有下级会员信息
	 * @param parentId
	 * @throws ServiceException
	 * @return MessageObject
	 */
	@SuppressWarnings("rawtypes")
	public Map queryAllLowerLevelMembers(Integer parentId) throws ServiceException {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
		try {
			List<Customer> customerslist = new ArrayList<Customer>();
			customerslist = customerInterfaceImplDao.getCustomerListByParentId(parentId);
			Integer vipcount = 0;
			if (customerslist != null && customerslist.size() >= 0) {
				for (Customer c : customerslist) {
					Map<String, Object> tempMap = new HashMap<String, Object>();
					tempMap.put("alias", c.getAlias());
					tempMap.put("createDate", c.getCreateDate().getTime());
					dataList.add(tempMap);
				}

				map.put("totalcount", customerslist.size());
				map.put("children", dataList);
				map.put("vipcount", vipcount);
				map.put("commoncount", (customerslist.size() - vipcount));
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, map);
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SELECT_ERROR);
			}
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error(e);
			throw new ServiceException(e);
		}

		return resultMap;
	}

	/**
	 * 
	 * @MethodName queryOrdersListCntByStatus
	 * @Description 个人中心统计“未支付，已支付，待评价商品数量”
	 * 
	 * @author chenpy
	 * @date 2015年12月28日 下午2:19:56
	 * @param
	 * @return Map
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map queryOrdersListCntByStatus(Customer customer, Integer mallType) throws ServiceException {
		Map resultMap = new HashMap();
		try {
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, this.customerInterfaceImplDao.queryOrdersListCntByStatus(customer, mallType));
			return resultMap;
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/**
	 * @Package com.sayimo.maker.user.service.impl
	 * @Author 龚益君
	 * @MethodName:makerLogin
	 * @Description:login
	 * @param customer
	 * @return
	 * @Date 2016年12月30日,上午10:16:11
	 */
	@Override
	public Map<String, Object> makerLogin(Customer customer) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {

			if (StringUtils.isEmpty(customer.getAccout()) || StringUtils.isEmpty(customer.getPassWord())) {
				logger.error("params error");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			Integer count = 0;
			Customer customer1 = new Customer();
			customer1.setPassWord(MD5Util.MD5Encode(CbcEncrypt.encrypt(customer.getPassWord()), "UTF-8"));
			customer1.setAccout(customer.getAccout());
			// 查询用户信息
			List<Customer> customerList = new ArrayList<>();
			customerList = customerInterfaceImplDao.queryCustomerByCond(customer1);
			if (!customerList.isEmpty() && customerList.size() != 0) {
				count = 1;
			} else {
				Customer customer2 = new Customer();
				customer2.setPassWord(MD5Util.MD5Encode(CbcEncrypt.encrypt(customer.getPassWord()), "UTF-8"));
				customer2.setMobilePhone(customer.getMobilePhone());
				customerList = customerInterfaceImplDao.queryCustomerByCond(customer2);
				if (!customerList.isEmpty() && customerList.size() != 0) {
					count = 2;
				}
			}
			if (count <= 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.PROVIDER_LOGINPWD_EXIT_ERROR);
				return resultMap;
			}
			customerList.get(0).setDeviceToken(customer.getDeviceToken());
			customerList.get(0).setDeviceType(customer.getDeviceType());
			customerInterfaceImplDao.updateCustomer(customerList.get(0));

			Map<String, Object> map = new HashMap<String, Object>();
			Long time = new Date().getTime();
			String signKey = DES3.encode("SAYIMO_MAKER_" + time);
			logger.info("&&&&&&&&&&&&&&&&&&&&customerId==" + customerList.get(0).getId());
			String signValue = DES3.encode(
					time + "|" + customerList.get(0).getId() + "|" + customerList.get(0).getAccout() + "|" + time);
			RedisUtils.put(signKey, signValue);

			customerList.get(0).setSayimoToken(signKey);
			map.put("customerInfo", customerList.get(0));
			resultMap.put(Constant.DATA, map);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return resultMap;
	}

	/**
	 * @Package com.sayimo.maker.user.service.impl
	 * @Author 龚益君
	 * @MethodName:makerRegister
	 * @Description:注册 maker客户端
	 * @param customer
	 * @return
	 * @Date 2016年12月30日,上午10:03:13
	 */
	@Override
	public Map<String, Object> makerRegister(Customer customer, String url) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		// 插入账号
		Integer count;
		try {
			if (customer.getInviteCode() != null && !customer.getInviteCode().equals("")) {
				Customer parent = new Customer();
				parent.setInviteCode(customer.getInviteCode());
				List<Customer> list = customerInterfaceImplDao.queryCustomerByCond(parent);
				if (list == null || list.isEmpty()) {
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					resultMap.put(Constant.ERROR_CODE, Constant.INVITECODE_NOT_EXIST);
					return resultMap;
				} else {
					customer.setParentId(list.get(0).getId());
					customer.setOwnAwardRule(list.get(0).getOwnAwardRule());
				}
			}
			count = customerInterfaceImplDao.queryCountByAccount(customer.getAccout());
			Customer check = new Customer();
			check.setMobilePhone(customer.getMobilePhone());
			List<Customer> list = customerInterfaceImplDao.queryCustomerByCond(check);
			if (count > 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.PROVIDER_ACCOUNT_EXIT_ERROR);
				return resultMap;
			}
			if (!list.isEmpty() || list.size() > 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.PROVIDER_MOBILEPHONE_EXIT_ERROR);
				return resultMap;
			}
			customer.setPassWord(MD5Util.MD5Encode(CbcEncrypt.encrypt(customer.getPassWord()), "UTF-8"));
			customer.setInviteCode(inviteCodeNo());
			customer.setAlias("SAYIMO_" + customer.getMobilePhone().substring(5));
			customer.setMatrixUrl("TXSX");
			// 生成二维码
			count = customerInterfaceImplDao.insertCustomer(customer);
			// 设置二维码内容
			String content = PropertiesUtils.getValue("SERVER_URL")
					+ "markerClient/view/me/scanQRCode/scanQRCode.html?customerId=" + customer.getId()
					+ "&customerAccount=" + customer.getAccout() + "&inviteCode=" + customer.getInviteCode();
			String path = PropertiesUtils.getValue("UPLOAD_FILE_PATH") + PropertiesUtils.getValue("FILE_SAVE_PATH")
					+ "/other";
			MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
			Map hints = new HashMap();
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);
			File file1 = new File(path, "ACCOUNT_QR_CODE.jpg");
			MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);

			InputStream in = null;
			byte[] data = null;
			// 读取图片字节数组
			try {
				in = new FileInputStream(file1.getPath());
				data = new byte[in.available()];
				in.read(data);
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 对字节数组Base64编码
			BASE64Encoder encoder = new BASE64Encoder();
			String fileStr = encoder.encode(data);// 返回Base64编码过的字节数组字符串
			String filePath = PropertiesUtils.getValue("FILE_SAVE_PATH") + "/other";
			String imagePath = PropertiesUtils.getValue("OTHERIMGPATH");
			UploadFileResult uploadResult = Base64Utils.uploadByBase64(PropertiesUtils.getValue("UPLOAD_SERVER_BASE64"),
					fileStr, "用户二维码.jpg", filePath, imagePath);
			UploadFileInfo fileInfo = uploadResult.getFiles()[0];
			String matrixLink = String.valueOf(fileInfo.getFileUrl() + "/" + fileInfo.getProFileName());
			if (matrixLink != null) {
				customer.setMatrixUrl(matrixLink);
			} else {
				customer.setMatrixUrl("www.baidu.com");
			}
			count = customerInterfaceImplDao.updateCustomer(customer);
			if (count > 0) {
				Wallet wallet = new Wallet();
				wallet.setCustomerId(customer.getId());
				walletInterfaceImplService.insertWallet(customer.getId());
				if (customer.getParentId() != null) {
					// 如果有上级则奖励上级发展下线银积分
					Integer sysValue = 0;
					// 获取上级钱包
					Wallet pwallet = walletInterfaceImplService.queryWalletByCustomerId(customer.getParentId());
					// 获取配置的奖励银积分
					sysValue = Integer.valueOf(baseConfigDao.getConfigByKey("MEMBER_DEVELOP_DOWN"));
					// 上级钱包累计银积分和银积分余额增加
					BigDecimal remainingSilverScore = new BigDecimal(
							sysValue + pwallet.getRemainingSilverScore().doubleValue());
					BigDecimal accumulaSilverScore = new BigDecimal(
							sysValue + pwallet.getAccumulaSilverScore().doubleValue());
					pwallet.setRemainingSilverScore(remainingSilverScore);
					pwallet.setAccumulaSilverScore(accumulaSilverScore);
					// 更新上级钱包
					count = walletInterfaceImplService.updateWallet(pwallet);
					if (count > 0) {
						// 为上级插入该次收入支出记录
						WalletIncomeExpendRecord incomeExpendRecord = new WalletIncomeExpendRecord();
						incomeExpendRecord.setRewardType(1); // 银积分奖励
						incomeExpendRecord.setCustomerId(customer.getParentId());
						incomeExpendRecord.setEmsNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
						incomeExpendRecord.setInCome(new BigDecimal(sysValue));
						incomeExpendRecord.setCommet("会员发展下线赠送银积分");
						incomeExpendRecord.setOrderType(6);
						incomeExpendRecord.setFromType(7);
						walletIncomeExpendRecordServiceImpl.insertSelective(incomeExpendRecord);
					}
				}

				dataMap.put(Constant.MSG, "注册成功");
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, dataMap);
			}

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * @Package com.sayimo.maker.user.service.impl
	 * @Author 谭新
	 * @MethodName: createQrCode
	 * @Description:重新生成二维码
	 * @Date 2017年4月6日,上午11:22:15
	 */
	@Override
	public Map<String, Object> createQrCode(String qrCodeUrl) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		// 插入账号
		Integer count;
		try {
			List<Customer> customerList = customerInterfaceImplDao.queryCustomerInfoByTime();
			for (Customer customer : customerList) {
				// 设置二维码内容
				String content = "https://maker.sayimo.cn/markerClient/view/me/scanQRCode/scanQRCode.html?customerId="
						+ customer.getId() + "&customerAccount=" + customer.getAccout() + "&inviteCode="
						+ customer.getInviteCode();
				logger.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%content=" + content);
				String path = PropertiesUtils.getValue("UPLOAD_FILE_PATH") + PropertiesUtils.getValue("FILE_SAVE_PATH")
						+ "/other";
				MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
				Map hints = new HashMap();
				hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
				BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);
				File file1 = new File(path, "ACCOUNT_QR_CODE.jpg");
				MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);

				InputStream in = null;
				byte[] data = null;
				// 读取图片字节数组
				try {
					in = new FileInputStream(file1.getPath());
					data = new byte[in.available()];
					in.read(data);
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				// 对字节数组Base64编码
				BASE64Encoder encoder = new BASE64Encoder();
				String fileStr = encoder.encode(data);// 返回Base64编码过的字节数组字符串
				String filePath = PropertiesUtils.getValue("FILE_SAVE_PATH") + "/other";
				String imagePath = PropertiesUtils.getValue("OTHERIMGPATH");
				UploadFileResult uploadResult = Base64Utils.uploadByBase64(
						PropertiesUtils.getValue("UPLOAD_SERVER_BASE64"), fileStr, "用户二维码.jpg", filePath, imagePath);
				UploadFileInfo fileInfo = uploadResult.getFiles()[0];
				String matrixLink = String.valueOf(fileInfo.getFileUrl() + "/" + fileInfo.getProFileName());
				if (matrixLink != null) {
					matrixLink = matrixLink;
				} else {
					matrixLink = "www.baidu.com";
				}
				customer.setMatrixUrl(matrixLink);
				customerInterfaceImplDao.updateCustomer(customer);
			}

			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, dataMap);

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * @Package com.sayimo.maker.user.service.impl
	 * @Author 龚益君
	 * @MethodName:validateAccount
	 * @Description:验证账号是否存在
	 * @param map
	 * @return
	 * @throws ServiceException
	 * @throws DaoException
	 * @Date 2016年12月30日,上午9:40:19
	 */
	public Map<String, Object> validateAccount(String account) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Integer count;
		try {
			count = customerInterfaceImplDao.queryCountByAccount(account);
			if (count > 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR, Constant.PROVIDER_ACCOUNT_EXIT_ERROR);
			} else {
				dataMap.put(Constant.MSG, "验证成功，账号和手机号可以使用");
				resultMap.put(Constant.DATA, dataMap);
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			}
		} catch (DaoException e) {
			logger.error(e);
			e.printStackTrace();
		}
		return resultMap;
	}

	@SuppressWarnings({ "unchecked", "rawtypes", "serial" })
	public Map updateUn_BindPhone(String mobilePhone, String customerId, String smsCode, String busCode)
			throws ServiceException {

		Map resultMap = new HashMap();
		Customer customer = new Customer();
		// 验证短信验证码是否正确
		SmsVerifyCode paramVerifyCode = new SmsVerifyCode();
		paramVerifyCode.setActionName(busCode);
		if (Constant.SMS_BUS_CODE_003.equals(busCode)) { // 解绑
			customer.setMobilePhone("");
		}
		paramVerifyCode.setMobilePhone(mobilePhone);
		SmsVerifyCode code = smsVerifyCodeInterfaceImplService.querySmsVerifyCodeByCond(paramVerifyCode);

		if (code == null) { // 短信验证码为空或者没有给该手机发送过短信验证码
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.VERIFY_CODE_NOT_EXISTS);
			return resultMap;
		}
		if (code.getLoseTime().getTime() < (new Date()).getTime()) { // 短信验证码已过期
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.VERIFY_CODE_BEYOND_LOSETIME);
			return resultMap;
		}
		if (!code.getVerifyCode().equals(smsCode)) { // 验证码不正确
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.VERIFY_CODE_ERROR);
			return resultMap;
		}
		customer.setId(Integer.parseInt(customerId));
		Map<String, Object> messageObject = updateCustomer(customer);
		final String resultCode = busCode.equals(Constant.SMS_BUS_CODE_002) ? "绑定" : "解绑";
		if (Constant.STATUS_SUCCESS.equals(messageObject.get(Constant.STATUS))) { // 修改成功
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, new HashMap() {
				{
					put(Constant.MSG, resultCode + "成功");
				}
			});
			return resultMap;
		} else {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			return resultMap;
		}
	}

	public Map<String, Object> updateCustomer(Customer customer) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		Map<String, Object> map = new HashMap<>();
		try {
			int result = this.customerInterfaceImplDao.updateCustomer(customer);
			if (result > 0) {
				map.put(Constant.MSG, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, map);

			} else {
				map.put(Constant.MSG, Constant.STATUS_ERROR);
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.DATA, map);

			}
			return resultMap;
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/**
	 * 
	 * @Title: updatePassword
	 * @Author: 田超
	 * @Date:日期：2016年12月3日 时间：上午10:59:39
	 * @Description: 忘记密码情况下密码修改
	 * @return
	 * @throws ServiceException
	 * @return Map<String,Object>
	 * @Version 1.0.0
	 */
	public Map<String, Object> updatePassword(HttpServletRequest request) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Customer account = new Customer();
			String mobilePhone = request.getParameter("mobilePhone");
			String newPassword = Base64Utils.decodeBase64(request.getParameter("newPassWord")); // 新密码
			String confirmPassword = Base64Utils.decodeBase64(request.getParameter("confirmPassword")); // 确认密码
			Customer customer = customerInterfaceImplDao.queryBymobilePhone(mobilePhone);
			if (customer == null || customer.getAccout() == null) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.PROVIDER_ACCOUNT_NOT_EXIST);
				return resultMap;
			} else if (newPassword.equals(confirmPassword)) {
				account.setPassWord(MD5Util.mD5Code(CbcEncrypt.encrypt(newPassword)));
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.PROVIDER_PASSWORD_NOT_EQUAL);
				return resultMap;
			}
			account.setAccout(customer.getAccout());
			Integer count = customerInterfaceImplDao.updateCustomer(account);
			if (count > 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, Constant.SUCCESS);
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			}
		} catch (Exception e) {
			logger.error(e);
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * 
	 * @Title: modifyPassword
	 * @Author: 田超
	 * @Date:日期：2016年12月5日 时间：上午10:28:15
	 * @Description: 自己修改密码
	 * @param account
	 * @return
	 * @throws ServiceException
	 * @return Map<String,Object>
	 * @Version 1.0.0
	 */
	public Map<String, Object> updateModifyPassword(HttpServletRequest request) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Customer account = new Customer();
			account.setAccout((String) request.getAttribute("accout"));
			account.setPassWord(Base64Utils.decodeBase64(request.getParameter("passWord")));
			String newPassword = Base64Utils.decodeBase64(request.getParameter("newPassWord")); // 新密码
			String confirmPassword = Base64Utils.decodeBase64(request.getParameter("confirmPassword")); // 确认密码

			logger.info(newPassword);

			Customer customerAccount = customerInterfaceImplDao.queryByAccout(account.getAccout());
			String passWord = MD5Util.mD5Code(CbcEncrypt.encrypt(account.getPassWord()));
			if (!passWord.equals(customerAccount.getPassWord())) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.PROVIDER_PASSWORD_EXIT_ERROR);
			} else if (!newPassword.equals(confirmPassword)) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.PROVIDER_PASSWORD_NOT_EQUAL);
			} else {
				account.setPassWord(MD5Util.mD5Code(CbcEncrypt.encrypt(newPassword)));
				Integer count = customerInterfaceImplDao.updateCustomer(account);
				if (count > 0) {
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					resultMap.put(Constant.DATA, Constant.SUCCESS);
				} else {
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
				}
			}
		} catch (Exception e) {
			logger.error(e);
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * 
	 * @Title: modifyPhone
	 * @Author: 田超
	 * @Date:日期：2016年12月5日 时间：下午2:26:03
	 * @Description: 修改绑定手机
	 * @param account
	 * @return
	 * @throws ServiceException
	 * @return Map<String,Object>
	 * @Version 1.0.0
	 */
	public Map<String, Object> updateModifyPhone(HttpServletRequest request) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Customer account = new Customer();
			account.setMobilePhone(request.getParameter("mobilePhone"));
			List<Customer> customerList = customerInterfaceImplDao.queryCustomerByCond(account);
			Integer count = customerList.size();
			if (count > 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.PROVIDER_MOBILEPHONE_EXIT_ERROR);
				return resultMap;
			}
			account.setAccout((String) request.getAttribute("accout"));
			count = customerInterfaceImplDao.updateModifyPhone(account);
			if (count > 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, Constant.SUCCESS);
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			}
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * 
	 * @Title: clearProviderToken
	 * @Author: 田超
	 * @Date:日期：2016年12月12日 时间：下午2:13:17
	 * @Description: 退出账号
	 * @param providerAccout
	 * @return
	 * @throws ServiceException
	 * @return Map<String,Object>
	 * @Version 1.0.0
	 */
	public Map<String, Object> clearProviderToken(HttpServletRequest request) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			String accout = (String) request.getAttribute("accout");
			String sayimoToken = request.getParameter("sayimoToken");
			if (accout == null || accout.equals("")) {
				logger.error("params error");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			// 移除redis存放的token值
			RedisUtils.removeKey(sayimoToken);

			Customer account = new Customer();
			account.setAccout(accout);
			account.setDeviceType(0);
			account.setDeviceToken("主动退出账号");
			customerInterfaceImplDao.updateCustomer(account);
			dataMap.put(Constant.MSG, "退出成功");
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, dataMap);
		} catch (DaoException e) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * @package com.sayimo.maker.user.service
	 * @author chenpy
	 * @Title:
	 * @Description: 会员绑定银行卡
	 * @param
	 * @throws @return
	 * @date 2017-02-20 上午11:46:34
	 */
	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
	public Map<String, Object> bindBankCard() throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		Map paramsMap = RequestUtils.bindRequestParam(request, HashMap.class);
		logger.info("paramMap = " + paramsMap);

		// 验证必填字段
		String[] requiredFields = new String[] { "customerId", "bankBindUserName", "bankCodeNo", "bindType" };
		if (!RequestUtils.checkRequireKV(paramsMap, requiredFields)) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}

		String bankName = null;
		Integer bindType = MapUtils.getInteger(paramsMap, "bindType");
		if (bindType == 2) { // 绑定银行卡
			bankName = MapUtils.getString(paramsMap, "bankName");
			if (StringUtils.isEmpty(bankName)) { // 选择绑定银行时，银行名称必填项
				logger.info("bankName = " + bankName);
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
		}

		Integer customerId = MapUtils.getInteger(paramsMap, "customerId");
		logger.info("customerId = " + customerId);

		// 验证用户是否已经绑定过银行卡
		try {
			Wallet wallet = walletInterfaceDao.queryWalletByCustomerId(customerId);
			if (StringUtils.isNotEmpty(wallet.getBankBindUserName())) {
				logger.info("会员已经绑定了银行卡");
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.CUSTOMER_ALREADY_BIND_BANK_CARD);
				return resultMap;
			}

			BeanUtils.copyProperties(wallet, paramsMap);

			int count = walletInterfaceDao.updateWallet(wallet);
			if (count > 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				return resultMap;
			}

			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			return resultMap;

		} catch (DaoException | IllegalAccessException | InvocationTargetException e) {
			logger.error(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * @package com.sayimo.maker.user.service
	 * @author chenpy
	 * @Title:
	 * @Description:申请成为创客
	 * @param
	 * @throws @return
	 * @date 2017-02-20 上午11:47:56
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
	public Map<String, Object> applyMaker() throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		Map paramsMap = RequestUtils.bindRequestParam(request, HashMap.class);
		logger.info("paramMap = " + paramsMap);

		String[] requiredFields = { "makerLevel", "payType", "customerId", "ownAwardRule", "applyType" }; // 创客等级
		if (!RequestUtils.checkRequireKV(paramsMap, requiredFields)) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}

		Integer makerLevel = MapUtils.getInteger(paramsMap, "makerLevel"), // 创客级别
				payType = MapUtils.getInteger(paramsMap, "payType"), // 支付类型
																		// 1微信支付；2支付宝支付
				ownAwardRule = MapUtils.getInteger(paramsMap, "ownAwardRule"); // 下级给自己的奖励模式
																				// 0无
																				// 1现金奖励
																				// 2提成奖励
		String applyType = MapUtils.getString(paramsMap, "applyType");
		Double payPrice = makerLevel == 1 ? 598D : 298D; // 支付金额：金星创客598元，银星创客298元
		// Double payPrice = makerLevel == 1 ? 0.02D : 0.01D; //
		// 支付金额：金星创客598元，银星创客298元

		String goodsName = makerLevel == 1 ? "金星创客申请" : "银星创客申请", ordersNo = GeneratorUtils.generatorOrdersNo("001");

		Map<String, Object> payParamMap = new HashMap<>();
		payParamMap.put("goodsName", goodsName);
		payParamMap.put("ordersNo", ordersNo);
		payParamMap.put("payPrice", Double.valueOf(payPrice));

		payParamMap.put("_payPrice", Double.valueOf(payPrice));
		payParamMap.put("_ordersType", 1);
		payParamMap.put("_customerId", MapUtils.getInteger(paramsMap, "customerId"));
		payParamMap.put("_rewardType", ownAwardRule);
		logger.info("alipayParamMap = " + payParamMap);

		// 调用支付接口
		try {
			// 记录批次号
			String recordBatchCode = (new StringBuilder(String.valueOf(new Date().getTime()))
					.append(new RandomStringUtils().random(6, "0123456789"))).toString();
			// 收入支出记录（创客申请订单）
			Integer customerId = MapUtils.getInteger(paramsMap, "customerId");
			WalletIncomeExpendRecord expendRecord = new WalletIncomeExpendRecord();
			expendRecord.setEmsNo(ordersNo);
			String comment = makerLevel == 1 ? "金星创客" : "银星创客";
			expendRecord.setCommet("申请成为" + comment);
			expendRecord.setCustomerId(customerId);
			expendRecord.setOrderType(4); // 创客申请
			expendRecord.setStatus(0);
			expendRecord.setFromType(payType == 1 ? 4 : 5);
			expendRecord.setExPend(new BigDecimal(payPrice));
			expendRecord.setRewardType(2);
			expendRecord.setRecordBatchCode(recordBatchCode);
			walletIncomeExpendRecordInterfaceDao.insertSelective(expendRecord);

			if (payType == 1) { // 微信支付
				if (applyType.equals("APP")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				} else if (applyType.equals("WEB")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				} else if (applyType.equals("PC")) {
					resultMap = WXScanCodePay.weixin_pay(payParamMap, request);
				} else if (applyType.equals("WAP")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				}

			} else { // 支付宝支付
				if (applyType.equals("APP")) {
					resultMap = ALiPay.aliPayOrder(payParamMap);
				} else if (applyType.equals("WAP")) {
					resultMap = AliWapPay.aliWapPayOrder(payParamMap);
				} else if (applyType.equals("PC")) {
					resultMap = AliScancodePay.creatOrCode(payParamMap);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * @package com.sayimo.maker.user.service
	 * @author chenpy
	 * @Title:
	 * @Description:创客申请回调
	 *                     <p>
	 *                     一、银星创客： 缴纳298元，奖励上级50元现金，获得298个银积分 二、金星创客:
	 *                     缴纳598元，奖励上级50元现金，获得798个银积分
	 * @param customerId
	 * @param tradeNo
	 *            订单号
	 * @param payType
	 *            1 微信支付 2 支付宝支付
	 * @throws @return
	 * @date 2017-02-20 下午4:33:16
	 */
	@SuppressWarnings({ "static-access", "unchecked", "rawtypes" })
	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
	public Map<String, Object> applyMakerCallback(Integer customerId, String tradeNo, Integer ownAwardRule)
			throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		try {
			WalletIncomeExpendRecord walletIncomeExpendRecord = walletIncomeExpendRecordInterfaceDao
					.getWalletIncomeExpendByEmsNo(tradeNo);
			if (walletIncomeExpendRecord.getStatus() == 2) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				return resultMap;
			}

			String payPrice = String.valueOf(walletIncomeExpendRecord.getExPend());
			Integer fromType = walletIncomeExpendRecord.getFromType();

			boolean isPaySuccess = false;
			if (fromType == 4) { // 微信支付
				isPaySuccess = WXPay.orderQuery(tradeNo);
			} else if (fromType == 5) { // 支付宝支付
				isPaySuccess = ALiPay.validAlipayTradeQuery(tradeNo);
			}

			if (isPaySuccess) { // 创客申请成功

				Integer makerLevel = Double.valueOf(payPrice).compareTo(298D) == 0 ? 2 : 1;
				// Integer makerLevel =
				// Double.valueOf(payPrice).compareTo(0.01D)==0 ? 2 : 1;

				logger.info("makerLevel = " + makerLevel);
				Customer customer = customerInterfaceImplDao.queryMemberCustomerById(customerId);
				customer.setMakerLevel(makerLevel);
				customer.setOwnAwardRule(ownAwardRule);
				customerInterfaceImplDao.updateCustomer(customer);

				walletIncomeExpendRecord.setStatus(2);
				walletIncomeExpendRecordInterfaceDao.updateWalletIncomeExpend(walletIncomeExpendRecord);

				// 申请成为创客积分赠送
				Double silverScore = Double.valueOf(baseConfigDao
						.getConfigByKey(makerLevel == 1 ? "GOLD_UPGRADE_SLIVER_SCORE" : "SILVER_UPGRADE_SLIVER_SCORE"));

				WalletIncomeExpendRecord ownIncomeExpendRecord = new WalletIncomeExpendRecord();
				// 收入支出记录
				ownIncomeExpendRecord.setRewardType(1); // 银积分奖励
				// 收入支出记录
				BigDecimal addOwnSilverScore = new BigDecimal(silverScore);
				ownIncomeExpendRecord.setCommet(
						"会员申请成为" + (makerLevel == 1 ? "金星创客" : "银星创客") + ",系统赠送" + addOwnSilverScore + "银积分");
				ownIncomeExpendRecord.setInCome(addOwnSilverScore);
				ownIncomeExpendRecord.setCustomerId(customerId);
				String ownEmsNo = (new StringBuilder(String.valueOf(new Date().getTime()))
						.append(new RandomStringUtils().random(6, "0123456789"))).toString();
				ownIncomeExpendRecord.setEmsNo(ownEmsNo);
				// 收入（支出）来源： 1、银行卡支付 2.钱包支付（现金） 3.钱包支付（银积分） 4微信支付 5支付宝支付 6系统退款
				// 7系统返现
				ownIncomeExpendRecord.setFromType(7);
				// 0代表普通订单，1代表预约订单，2代表课程订单 3充值银积分 4申请创客 5扫描联盟商二维码 6佣金收入 7现金提现
				ownIncomeExpendRecord.setOrderType(4);
				ownIncomeExpendRecord.setRecordBatchCode(walletIncomeExpendRecord.getRecordBatchCode());
				walletIncomeExpendRecordInterfaceDao.insertSelective(ownIncomeExpendRecord);

				// 查询钱包
				Wallet ownWallet = walletInterfaceDao.queryWalletByCustomerId(customerId);
				ownWallet.setAccumulaSilverScore(ownWallet.getAccumulaSilverScore().add(addOwnSilverScore));
				ownWallet.setRemainingSilverScore(ownWallet.getRemainingSilverScore().add(addOwnSilverScore));
				walletInterfaceDao.updateWallet(ownWallet);

				Integer parentId = customer.getParentId();
				logger.info("parentId = " + parentId);
				if (parentId == null) { // 会员没有上级
					logger.info("该会员无上级会员");
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					return resultMap;
				}

				Customer parentCustomer = customerInterfaceImplDao.queryMemberCustomerById(parentId);
				if (parentCustomer == null) {
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					return resultMap;
				}

				// 给上级奖励模式，取上级自定义的给自己的奖励模式
				customer.setAwardRule(parentCustomer.getOwnAwardRule());
				customerInterfaceImplDao.updateCustomer(customer);

				// 父级创客等级
				Integer parentMakerLevel = parentCustomer.getMakerLevel();
				logger.info("parentMakerLevel = " + parentMakerLevel);
				if (parentMakerLevel == null || (parentMakerLevel != 1 && parentMakerLevel != 2)) {
					logger.info("上级会员不是创客");
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					return resultMap;
				}

				// 奖励上级
				{
					Wallet wallet = walletInterfaceDao.queryWalletByCustomerId(parentId);
					// 判断父级创客等级 ，读取配置，(金星/银星)创客发展创客赠送现金和银积分
					// 现金奖励
					Double makerCash = Double.valueOf(baseConfigDao
							.getConfigByKey(parentMakerLevel == 1 ? "GOLD_MAKER_CASH" : "SILVER_MAKER_CASH"));
					// 积分奖励
					Double makerSilverScore = Double.valueOf(baseConfigDao.getConfigByKey(
							parentMakerLevel == 1 ? "GOLD_MAKER_SLIVER_SCORE" : "SILVER_MAKER_SLIVER_SCORE"));

					WalletIncomeExpendRecord incomeExpendRecord = new WalletIncomeExpendRecord();
					// 收入支出记录
					incomeExpendRecord.setRewardType(1); // 银积分奖励
					// 收入支出记录
					BigDecimal addSilverScore = new BigDecimal(makerSilverScore);
					incomeExpendRecord.setCommet(
							"下级会员申请成为" + (makerLevel == 1 ? "金星创客" : "银星创客") + ",系统奖励" + addSilverScore + "银积分");
					incomeExpendRecord.setInCome(addSilverScore);
					incomeExpendRecord.setCustomerId(parentId);
					String emsNo = (new StringBuilder(String.valueOf(new Date().getTime()))
							.append(new RandomStringUtils().random(6, "0123456789"))).toString();
					incomeExpendRecord.setEmsNo(emsNo);
					// 收入（支出）来源： 1、银行卡支付 2.钱包支付（现金） 3.钱包支付（银积分） 4微信支付 5支付宝支付
					// 6系统退款 7系统返现
					incomeExpendRecord.setFromType(7);
					// 0代表普通订单，1代表预约订单，2代表课程订单 3充值银积分 4申请创客 5扫描联盟商二维
					incomeExpendRecord.setOrderType(4);
					incomeExpendRecord.setRecordBatchCode(walletIncomeExpendRecord.getRecordBatchCode());
					walletIncomeExpendRecordInterfaceDao.insertSelective(incomeExpendRecord);

					wallet.setAccumulaSilverScore(wallet.getAccumulaSilverScore().add(addSilverScore));
					wallet.setRemainingSilverScore(wallet.getRemainingSilverScore().add(addSilverScore));
					wallet.setRemainingCash(wallet.getRemainingCash().add(new BigDecimal(makerCash)));
					wallet.setAccumulaCash(wallet.getAccumulaCash().add(new BigDecimal(makerCash)));
					Integer count = walletInterfaceDao.updateWallet(wallet);
					if (count > 0) { // 交易
						// 收入支出记录
						incomeExpendRecord = new WalletIncomeExpendRecord();
						incomeExpendRecord.setInCome(new BigDecimal(makerCash));
						incomeExpendRecord.setRewardType(2); // 现金奖励
						incomeExpendRecord.setCustomerId(parentId);
						incomeExpendRecord.setCommet("下级会员申请成为" + (makerLevel == 1 ? "金星创客" : "银星创客") + ",系统奖励50元");
						String emsNo1 = (new StringBuilder(String.valueOf(new Date().getTime()))
								.append(new RandomStringUtils().random(6, "0123456789"))).toString();
						incomeExpendRecord.setEmsNo(emsNo1);
						// 收入（支出）来源： 1、银行卡支付 2.钱包支付（现金） 3.钱包支付（银积分） 4微信支付 5支付宝支付
						// 6系统退款 7系统返现
						incomeExpendRecord.setFromType(7);
						// 0代表普通订单，1代表预约订单，2代表课程订单 3充值银积分 4申请创客 5扫描联盟商二维
						incomeExpendRecord.setOrderType(4);
						incomeExpendRecord.setRecordBatchCode(walletIncomeExpendRecord.getRecordBatchCode());
						walletIncomeExpendRecordInterfaceDao.insertSelective(incomeExpendRecord);
					}
				}

				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				return resultMap;
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * @package com.sayimo.maker.user.service
	 * @author chenpy
	 * @Title: rechargeSilverScore
	 * @Description: 会员充值（银积分）
	 * @param
	 * @throws @return
	 * @date 2017-02-21 上午10:54:15
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map<String, Object> rechargeSilverScore(String passWord) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		Map paramsMap = RequestUtils.bindRequestParam(request, HashMap.class);
		logger.info("paramMap = " + paramsMap);

		// 必填字段
		// totalRecharge充值金额；
		// payType 支付方式：1 微信支付2支付宝支付,3钱包支付（现金）
		// customerId会员ID
		String[] requiredFields = { "totalRecharge", "payType", "customerId", "applyType" };

		if (!RequestUtils.checkRequireKV(paramsMap, requiredFields)) { // 必填字段验证
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}

		// 验证输入金额
		String _payPrice = MapUtils.getString(paramsMap, "totalRecharge");
		String reg = "^([\\d]+)(\\.([\\d]{1,2}))?$";
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(_payPrice);

		if (!matcher.find()) { // 充值金额格式不正确
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.CUSTOMER_RECHARGE_SILVER_SCORE_PATTERN_ERROR);
			return resultMap;
		}

		String iGroup = matcher.group(1);
		// 整数部分全是0(00)或者是以0会开头（01）
		if (iGroup.startsWith("0") && iGroup.length() > 1) { // 充值金额格式不正确
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.CUSTOMER_RECHARGE_SILVER_SCORE_PATTERN_ERROR);
			return resultMap;
		}

		Double payPrice = Double.valueOf(_payPrice);
		Integer payType = MapUtils.getInteger(paramsMap, "payType");
		String ordersNo = GeneratorUtils.generatorOrdersNo("002");
		Integer customerId = MapUtils.getInteger(paramsMap, "customerId");
		String applyType = MapUtils.getString(paramsMap, "applyType");

		Map<String, Object> payParamMap = new HashMap<>();
		payParamMap.put("goodsName", "银积分充值");
		payParamMap.put("ordersNo", ordersNo);
		payParamMap.put("payPrice", payPrice);

		if (payType == 3) {
			// 判断钱包现金余额
			// 判断钱包密码
			Wallet wallet = walletInterfaceImplService.queryWalletByCustomerId(customerId);
			if (!wallet.getPassWord().equals(passWord)) { // 钱包密码不正确
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.WALLET_PASSWORD_ERROR);
				return resultMap;
			}

			Double remainingCash = wallet.getRemainingCash().doubleValue();
			if (payPrice <= 0) {
				payPrice = 0.00;
			}

			if (Double.compare(remainingCash, payPrice) < 0) { // 余额不足
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.AVAILABLE_MONEY_NOT_ENOUGH);
				return resultMap;
			}
		}

		// 设置回调参数
		payParamMap.put("_ordersType", 2);
		payParamMap.put("_customerId", MapUtils.getInteger(paramsMap, "customerId"));
		payParamMap.put("_payPrice", payPrice);
		logger.info("alipayParamMap = " + payParamMap);

		// 收入支出记录（银积分充值订单）
		// 银积分收入记录
		// 记录批次号
		String recordBatchCode = (new StringBuilder(String.valueOf(new Date().getTime()))
				.append(new RandomStringUtils().random(6, "0123456789"))).toString();

		WalletIncomeExpendRecord expendRecord = new WalletIncomeExpendRecord();
		expendRecord.setEmsNo(ordersNo);
		expendRecord.setCommet("充值银积分");
		expendRecord.setCustomerId(customerId);
		expendRecord.setRewardType(1);
		expendRecord.setOrderType(3); // 充值银积分
		expendRecord.setStatus(0);// 微信支付宝支付设置为0，回调时更改成正常
		if (payType == 1) {
			expendRecord.setFromType(4);
		} else if (payType == 2) {
			expendRecord.setFromType(5);
		} else if (payType == 3) {
			// 使用钱包现金充值
			expendRecord.setStatus(1);
			expendRecord.setFromType(2);
		}
		BigDecimal addSilverScore = new BigDecimal(_payPrice).multiply(new BigDecimal(3));
		expendRecord.setInCome(addSilverScore);
		expendRecord.setRecordBatchCode(recordBatchCode);

		// 调用支付接口
		try {
			walletIncomeExpendRecordInterfaceDao.insertSelective(expendRecord);

			if (payType == 1) { // 微信支付
				if (applyType.equals("APP")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				} else if (applyType.equals("WEB")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				} else if (applyType.equals("PC")) {
					resultMap = WXScanCodePay.weixin_pay(payParamMap, request);
				} else if (applyType.equals("WAP")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				}

			} else if (payType == 2) { // 支付宝支付
				if (applyType.equals("APP")) {
					resultMap = ALiPay.aliPayOrder(payParamMap);
				} else if (applyType.equals("WAP")) {
					resultMap = AliWapPay.aliWapPayOrder(payParamMap);
				} else if (applyType.equals("PC")) {
					resultMap = AliScancodePay.creatOrCode(payParamMap);
				}

			} else if (payType == 3) { // 使用钱包现金充值
				Wallet wallet = walletInterfaceDao.queryWalletByCustomerId(customerId);

				logger.info("addSilverScore = " + addSilverScore);

				// 增加银积分
				wallet.setAccumulaSilverScore(wallet.getAccumulaSilverScore().add(addSilverScore));
				wallet.setRemainingSilverScore(wallet.getRemainingSilverScore().add(addSilverScore));
				// 扣除钱包现金余额
				wallet.setRemainingCash(wallet.getRemainingCash().subtract(new BigDecimal(_payPrice)));
				walletInterfaceDao.updateWallet(wallet);

				// 收入支出记录（银积分充值订单）
				// 钱包现金支出记录
				WalletIncomeExpendRecord expendRecordCash = new WalletIncomeExpendRecord();
				expendRecordCash.setEmsNo(GeneratorUtils.generatorOrdersNo("002"));
				expendRecordCash.setCommet("充值银积分");
				expendRecordCash.setCustomerId(customerId);
				expendRecordCash.setRewardType(2);
				expendRecordCash.setOrderType(3); // 充值银积分
				// 使用钱包现金充值
				expendRecordCash.setStatus(1);
				expendRecordCash.setFromType(2);
				expendRecordCash.setExPend(new BigDecimal(_payPrice));
				expendRecordCash.setRecordBatchCode(recordBatchCode);
				walletIncomeExpendRecordInterfaceDao.insertSelective(expendRecordCash);

				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				return resultMap;
			}

			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * @package com.sayimo.maker.user
	 * @author chenpy
	 * @Title: rechargeSilverScoreCallback
	 * @Description:用户充值（银积分）回调
	 * @param
	 * @throws @return
	 * @date 2017-02-20 上午11:37:30
	 */
	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
	public synchronized Map<String, Object> rechargeSilverScoreCallback(Integer customerId, String tradeNo)
			throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		try {
			WalletIncomeExpendRecord walletIncomeExpendRecord = walletIncomeExpendRecordInterfaceDao
					.getWalletIncomeExpendByEmsNo(tradeNo);
			if (walletIncomeExpendRecord.getStatus() == 1) {
				logger.info("已经回调成功");
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				return resultMap;
			}

			Double payPrice = walletIncomeExpendRecord.getInCome().doubleValue();
			Integer fromType = walletIncomeExpendRecord.getFromType();

			boolean isPaySuccess = true;
			if (fromType == 4) { // 微信支付
				isPaySuccess = WXPay.orderQuery(tradeNo);
			} else if (fromType == 5) { // 支付宝支付
				isPaySuccess = ALiPay.validAlipayTradeQuery(tradeNo);
			}

			logger.info("payPrice = " + payPrice + ", customerId = " + customerId);
			if (isPaySuccess) { // 充值成功
				Wallet wallet = walletInterfaceDao.queryWalletByCustomerId(customerId);

				BigDecimal addSilverScore = new BigDecimal(payPrice);
				logger.info("addSilverScore = " + addSilverScore);

				wallet.setAccumulaSilverScore(wallet.getAccumulaSilverScore().add(addSilverScore));
				wallet.setRemainingSilverScore(wallet.getRemainingSilverScore().add(addSilverScore));
				walletInterfaceDao.updateWallet(wallet);

				walletIncomeExpendRecord.setStatus(1);
				walletIncomeExpendRecordInterfaceDao.updateWalletIncomeExpend(walletIncomeExpendRecord);

				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				return resultMap;
			}

			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * @package com.sayimo.maker.user.service
	 * @author wangyang
	 * @Title: unionScanCodePay
	 * @Description: 用户扫联盟商二维码支付
	 * @param
	 * @throws DaoException
	 * @throws @return
	 * @date 2017-03-07 下午16:38:30
	 */
	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
	public Map<String, Object> unionScanCodePay() throws Exception {
		Map<String, Object> resultMap = new HashMap<>();
		Map paramsMap = RequestUtils.bindRequestParam(request, HashMap.class);
		logger.info("paramMap = " + paramsMap);
		// 必填字段 totalRecharge 充值金额; payType 支付方式：1 微信支付 2 支付宝支付; customerId
		// 联盟商会员ID; fromCustomerId 扫码会员ID
		String[] requiredFields = { "totalRecharge", "payType", "customerId", "fromCustomerId", "applyType" };
		if (!RequestUtils.checkRequireKV(paramsMap, requiredFields)) { // 必填字段验证
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}

		// 验证输入金额
		String _payPrice = MapUtils.getString(paramsMap, "totalRecharge");
		String reg = "^([\\d]+)(\\.([\\d]{1,2}))?$";
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(_payPrice);

		if (!matcher.find()) { // 充值金额格式不正确
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.CUSTOMER_RECHARGE_SILVER_SCORE_PATTERN_ERROR);
			return resultMap;
		}

		String iGroup = matcher.group(1);
		// 整数部分全是0(00)或者是以0会开头（01）
		if (iGroup.startsWith("0") && iGroup.length() > 1) { // 充值金额格式不正确
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.CUSTOMER_RECHARGE_SILVER_SCORE_PATTERN_ERROR);
			return resultMap;
		}

		Double payPrice = Double.valueOf(_payPrice);
		Integer payType = MapUtils.getInteger(paramsMap, "payType");
		String applyType = MapUtils.getString(paramsMap, "applyType");
		String producerOrdersNo = GeneratorUtils.generatorOrdersNo("005");
		String consumerOrdersNo = GeneratorUtils.generatorOrdersNo("005");
		String recordBatchCode = GeneratorUtils.generatorOrdersNo("005");
		// 收入支出记录（创客申请订单）
		Integer customerId = MapUtils.getInteger(paramsMap, "customerId");
		Integer fromCustomerId = MapUtils.getInteger(paramsMap, "fromCustomerId");
		EnterpriseInfo enterpriseInfo = enterpriseInfoDao.getEnterpriseInfoByCustomerId(customerId);
		int serviceCharge = enterpriseInfo.getServiceCharge(); // 联盟商认证平台服务费
		logger.info("serviceCharge = " + serviceCharge);
		BigDecimal unionPayPrice = new BigDecimal(payPrice).multiply(new BigDecimal(100 - serviceCharge))
				.divide(new BigDecimal(100));
		logger.info("unionPayPrice = " + unionPayPrice);

		Map<String, Object> payParamMap = new HashMap<>();
		payParamMap.put("goodsName", "扫描联盟商二维码");
		payParamMap.put("ordersNo", producerOrdersNo);
		payParamMap.put("payPrice", payPrice);
		payParamMap.put("consumerOrdersNo", consumerOrdersNo);

		// 设置回调参数
		payParamMap.put("_ordersType", 4);
		payParamMap.put("_customerId", MapUtils.getInteger(paramsMap, "customerId"));
		payParamMap.put("_payPrice", payPrice);
		payParamMap.put("_consumerOrdersNo", consumerOrdersNo);
		logger.info("alipayParamMap = " + payParamMap);

		// 联盟商转账记录
		Customer producerCustomer = customerInterfaceImplDao.queryMemberCustomerById(customerId); // 获取联盟商信息
		EnterpriseWallet enterpriseWallet = enterpriseWalletInterfaceDao
				.queryWalletByCustomerId(producerCustomer.getProviderRefId());
		EnterpriseWalletIncomeExpendRecord producerExpendRecord = new EnterpriseWalletIncomeExpendRecord();
		if (enterpriseWallet.getBindType() - 1 == 0) {
			// unionPayPrice = unionPayPrice.multiply(new BigDecimal(1 -
			// 0.006));//扣除手续费（暂时不扣）
			producerExpendRecord.setEmsNo(producerOrdersNo);
			producerExpendRecord.setCommet("转账给联盟商获取营业额货款");
			producerExpendRecord.setProviderRefId(producerCustomer.getProviderRefId());
			producerExpendRecord.setRewardType(2);
			producerExpendRecord.setOrderType(5); // 扫描联盟商二维码
			producerExpendRecord.setStatus(0);
			producerExpendRecord.setTransferStatus(3);
			producerExpendRecord.setFromType(5);
			producerExpendRecord.setRecordBatchCode(recordBatchCode);
			producerExpendRecord.setInCome(unionPayPrice);
			producerExpendRecord.setTurnover(new BigDecimal(payPrice));
		} else {
			producerExpendRecord.setEmsNo(producerOrdersNo);
			producerExpendRecord.setCommet("转账给联盟商获取营业额货款");
			producerExpendRecord.setProviderRefId(producerCustomer.getProviderRefId());
			producerExpendRecord.setRewardType(2);
			producerExpendRecord.setOrderType(5); // 扫描联盟商二维码
			producerExpendRecord.setStatus(0);
			producerExpendRecord.setTransferStatus(1);
			producerExpendRecord.setFromType(1);
			producerExpendRecord.setRecordBatchCode(recordBatchCode);
			producerExpendRecord.setInCome(unionPayPrice);
			producerExpendRecord.setTurnover(new BigDecimal(payPrice));
		}
		// 消费者交易记录
		WalletIncomeExpendRecord consumerExpendRecord = new WalletIncomeExpendRecord();
		consumerExpendRecord.setEmsNo(consumerOrdersNo);
		consumerExpendRecord.setCommet("扫描联盟商二维码用户交易记录");
		consumerExpendRecord.setCustomerId(fromCustomerId);
		consumerExpendRecord.setOrderType(5); // 扫描联盟商二维码
		consumerExpendRecord.setStatus(0);
		consumerExpendRecord.setFromType(payType == 1 ? 4 : 5);
		consumerExpendRecord.setExPend(new BigDecimal(payPrice));
		consumerExpendRecord.setRewardType(2);
		consumerExpendRecord.setRecordBatchCode(recordBatchCode);
		// 调用支付接口
		try {
			walletIncomeExpendRecordInterfaceDao.insertSelective(consumerExpendRecord);

			enterpriseWalletIncomeExpendRecordInterfaceDao.insertSelective(producerExpendRecord);

			if (payType == 1) { // 微信支付
				if (applyType.equals("APP")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				} else if (applyType.equals("WEB")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				} else if (applyType.equals("PC")) {
					resultMap = WXScanCodePay.weixin_pay(payParamMap, request);
				} else if (applyType.equals("WAP")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				}

			} else { // 支付宝支付
				if (applyType.equals("APP")) {
					resultMap = ALiPay.aliPayOrder(payParamMap);
				} else if (applyType.equals("WAP")) {
					resultMap = AliWapPay.aliWapPayOrder(payParamMap);
				} else if (applyType.equals("PC")) {
					resultMap = AliScancodePay.creatOrCode(payParamMap);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * @package com.sayimo.maker.user.service
	 * @author wangyang
	 * @Title: unionScanCodePayCallback
	 * @Description: 用户扫联盟商二维码支付回调
	 * @param
	 * @throws @return
	 * @date 2017-03-07 下午17:31:08
	 */
	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
	public synchronized Map<String, Object> unionScanCodePayCallback(String tradeNo, String consumerOrdersNo)
			throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		try {

			EnterpriseWalletIncomeExpendRecord producerWalletIncomeExpendRecord = enterpriseWalletIncomeExpendRecordInterfaceDao
					.getWalletIncomeExpendByEmsNo(tradeNo);
			WalletIncomeExpendRecord consumerWalletIncomeExpendRecord = walletIncomeExpendRecordInterfaceDao
					.getWalletIncomeExpendByEmsNo(consumerOrdersNo);
			if (consumerWalletIncomeExpendRecord.getStatus() == 1) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				return resultMap;
			}
			BigDecimal payPrice = producerWalletIncomeExpendRecord.getInCome();
			Integer fromType = producerWalletIncomeExpendRecord.getFromType();
			boolean isPaySuccess = true;
			if (fromType == 4) { // 微信支付验证
				isPaySuccess = WXPay.orderQuery(tradeNo);
			} else if (fromType == 5) { // 支付宝支付回调验证
				isPaySuccess = ALiPay.validAlipayTradeQuery(tradeNo);
			}

			logger.info("payPrice = " + payPrice);

			if (isPaySuccess) { // 支付成功
				// 修改用户交易记录状态
				consumerWalletIncomeExpendRecord.setStatus(1);
				walletIncomeExpendRecordInterfaceDao.updateWalletIncomeExpend(consumerWalletIncomeExpendRecord);
				// 购买联盟商商品后按照一定比例赠送银积分：
				// 获取当前会员的id
				Integer fromCustomerId = consumerWalletIncomeExpendRecord.getCustomerId();
				Wallet wallet = walletInterfaceImplService.queryWalletByCustomerId(fromCustomerId);
				// 获取银积分奖励百分比
				Double sysValue = Double.parseDouble(baseConfigDao.getConfigByKey("UNION_CONSUMER_SCORE")) / 100D;
				// 设置银积分/银积分累计收入
				// 用户消费金额
				Double _payPrice = consumerWalletIncomeExpendRecord.getExPend().doubleValue();
				BigDecimal remainingSilverScore = new BigDecimal(
						_payPrice * sysValue + wallet.getRemainingSilverScore().doubleValue());
				BigDecimal accumulaSilverScore = new BigDecimal(
						_payPrice * sysValue + wallet.getAccumulaSilverScore().doubleValue());
				wallet.setRemainingSilverScore(remainingSilverScore);
				wallet.setAccumulaSilverScore(accumulaSilverScore);
				Integer count = walletInterfaceImplService.updateWallet(wallet);
				if (count > 0) {
					// 收入支出记录
					WalletIncomeExpendRecord incomeExpendRecord = new WalletIncomeExpendRecord();
					incomeExpendRecord.setRewardType(1); // 银积分奖励
					incomeExpendRecord.setCustomerId(fromCustomerId);
					incomeExpendRecord.setEmsNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
					incomeExpendRecord.setInCome(new BigDecimal(_payPrice * sysValue));
					incomeExpendRecord.setCommet("用户在联盟商消费赠送银积分");
					incomeExpendRecord.setOrderType(6);
					incomeExpendRecord.setFromType(7);
					incomeExpendRecord.setRecordBatchCode(consumerWalletIncomeExpendRecord.getRecordBatchCode());
					incomeExpendRecord.setOrderId(-consumerWalletIncomeExpendRecord.getId());
					walletIncomeExpendRecordServiceImpl.insertSelective(incomeExpendRecord);
				}
				// 转账到联盟商上级钱包
				String higherLeverRewardStatus = unionScanCodeHigherLeverReward(producerWalletIncomeExpendRecord);
				if (!"SUCCESS".equals(higherLeverRewardStatus)) {
					resultMap.put(Constant.STATUS, Constant.SYSTEM_ERROR);
					return resultMap;
				}
				// 转账给联盟商
				String unionRewardStatus = unionScanCodeUnionReward(producerWalletIncomeExpendRecord,
						consumerWalletIncomeExpendRecord);
				if (!"SUCCESS".equals(unionRewardStatus)) {
					resultMap.put(Constant.STATUS, Constant.SYSTEM_ERROR);
					return resultMap;
				}

				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				return resultMap;
			}

			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * @package com.sayimo.maker.user.service
	 * @author wangyang
	 * @Title: unionScanCodeHigherLeverReward
	 * @Description: 向联盟商上级转账到其钱包
	 * @param
	 * @throws @return
	 * @date 2017-03-13 上午11:31:08
	 */
	private String unionScanCodeHigherLeverReward(EnterpriseWalletIncomeExpendRecord producerWalletIncomeExpendRecord)
			throws ServiceException {
		try {
			Integer providerRefId = producerWalletIncomeExpendRecord.getProviderRefId();// 联盟商id
			List<Integer> providerIds = new ArrayList<>();
			providerIds.add(providerRefId);
			Customer producerCustomer = new Customer(); // 联盟商会员
			Customer parentProducerCustomer = new Customer(); // 联盟商上级会员
			BigDecimal pushMoney = new BigDecimal(0);
			EnterpriseInfo enterpriseInfo = enterpriseInfoDao.getEnterpriseInfoByIds(providerIds).get(0);
			Integer producerCustomerId = enterpriseInfo.getCustomerId();
			int serviceCharge = enterpriseInfo.getServiceCharge(); // 联盟商认证平台服务费百分比
			logger.info("serviceCharge = " + serviceCharge);
			BigDecimal payPrice = producerWalletIncomeExpendRecord.getInCome().multiply(new BigDecimal(100))
					.divide(new BigDecimal(100 - serviceCharge));
			logger.info("payPrice = " + payPrice);
			// Integer fromType =
			// producerWalletIncomeExpendRecord.getFromType();
			if (producerCustomerId != null && producerCustomerId != 0) {
				producerCustomer = customerInterfaceImplDao.queryMemberCustomerById(producerCustomerId); // 获取联盟商信息
				if (producerCustomer.getParentId() != null && producerCustomer.getParentId() != 0) {
					// 获取联盟商上级会员信息
					parentProducerCustomer = customerInterfaceImplDao
							.queryMemberCustomerById(producerCustomer.getParentId());
					Wallet wallet = walletInterfaceImplService.queryWalletByCustomerId(producerCustomer.getParentId());
					if (parentProducerCustomer.getMakerLevel() > 0 && producerCustomer.getAwardRule() - 2 == 0) {
						// 联盟商提成奖励
						// 根据设置规则向联盟商上级会员转账
						// Map tParamMap = new HashMap();
						/*
						 * String payeeAccount = wallet.getBankCodeNo(); //
						 * 捆绑收款支付宝账号 String payeeRealName =
						 * wallet.getBankBindUserName(); // 捆绑支付宝用户名
						 */ if (parentProducerCustomer.getMakerLevel() - 1 == 0) { // 金星创客联盟商提成奖励模式
							// 金星创客发展一个联盟商提成奖励模式折扣小于等于
							int rateRuleLT = Integer.parseInt(baseConfigDao.getConfigByKey("GOLD_UNION_COMMISSION_LT"));
							logger.info("rateRuleLT = " + rateRuleLT);
							// 金星创客发展一个联盟商提成奖励模式折扣大于
							int rateRuleGT = Integer.parseInt(baseConfigDao.getConfigByKey("GOLD_UNION_COMMISSION_GT"));
							logger.info("rateRuleGT = " + rateRuleGT);

							if (serviceCharge <= rateRuleLT) {
								// 销售额提成 :例如：0.5/100 =0.5%(以销售额100为例)
								BigDecimal sysValueLt = new BigDecimal(
										baseConfigDao.getConfigByKey("GOLD_UNION_COMMISSION_SALES"))
												.divide(new BigDecimal(100));
								// 奖励金额: 100x0.5%=0.5
								pushMoney = payPrice.multiply(sysValueLt);
							} else if (serviceCharge > rateRuleGT) {
								BigDecimal sysValueGt = new BigDecimal(
										baseConfigDao.getConfigByKey("GOLD_UNION_COMMISSION_EQUALLY"))
												.divide(new BigDecimal(100));

								// 100x(30%-20%)x50/100=5
								pushMoney = payPrice
										.multiply(
												new BigDecimal(serviceCharge - rateRuleGT).divide(new BigDecimal(100)))
										.multiply(sysValueGt).divide(new BigDecimal(100));

								logger.info("GoldPushMoney = " + pushMoney);
							}
						} else { // 银星创客联盟商提成奖励模式(参照金星创客)
							// 银星创客发展一个联盟商提成奖励模式折扣小于等于
							int rateRuleLT = Integer
									.parseInt(baseConfigDao.getConfigByKey("SILVER_UNION_COMMISSION_LT"));
							logger.info("rateRuleLT = " + rateRuleLT);
							// 银星创客发展一个联盟商提成奖励模式折扣大于
							int rateRuleGT = Integer
									.parseInt(baseConfigDao.getConfigByKey("SILVER_UNION_COMMISSION_GT"));
							logger.info("rateRuleGT = " + rateRuleGT);

							if (serviceCharge <= rateRuleLT) {
								BigDecimal sysValueLt = new BigDecimal(
										baseConfigDao.getConfigByKey("SILVER_UNION_COMMISSION_SALES"))
												.divide(new BigDecimal(100));

								pushMoney = payPrice.multiply(sysValueLt); // 联盟商上级会员提成奖励
							} else if (serviceCharge > rateRuleGT) {
								BigDecimal sysValueGt = new BigDecimal(
										baseConfigDao.getConfigByKey("SILVER_UNION_COMMISSION_EQUALLY"))
												.divide(new BigDecimal(100));

								pushMoney = payPrice
										.multiply(
												new BigDecimal(serviceCharge - rateRuleGT).divide(new BigDecimal(100)))
										.multiply(sysValueGt).divide(new BigDecimal(100));// 联盟商上级会员提成奖励
								logger.info("SilverPushMoney = " + pushMoney);
							}
						}

						BigDecimal addCash = pushMoney.setScale(2, BigDecimal.ROUND_DOWN);
						logger.info("addCash = " + addCash);

						if (Double.valueOf(addCash.toString()) >= 0.01) {
							wallet.setRemainingCash(wallet.getRemainingCash().add(addCash));
							wallet.setAccumulaCash(wallet.getAccumulaCash().add(addCash));
							Integer count = walletInterfaceDao.updateWallet(wallet);
							if (count > 0) {
								// 收入支出记录
								WalletIncomeExpendRecord incomeExpendRecord = new WalletIncomeExpendRecord();
								incomeExpendRecord.setRewardType(2); // 现金奖励
								incomeExpendRecord.setCustomerId(parentProducerCustomer.getId());
								incomeExpendRecord.setInCome(addCash);
								incomeExpendRecord.setCommet("联盟商上级获取联盟商营业额提成");
								incomeExpendRecord.setEmsNo(GeneratorUtils.generatorOrdersNo("005"));
								incomeExpendRecord.setFromType(7);
								incomeExpendRecord.setOrderType(6);
								incomeExpendRecord
										.setRecordBatchCode(producerWalletIncomeExpendRecord.getRecordBatchCode());
								incomeExpendRecord.setOrderId(producerWalletIncomeExpendRecord.getOrderId());
								walletIncomeExpendRecordServiceImpl.insertSelective(incomeExpendRecord);
							}
						}

						return "SUCCESS";

					}
				} else {
					// 没有上级
					return "SUCCESS";
				}
			}

		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return "FAIL";
	}

	/**
	 * @package com.sayimo.maker.user.service
	 * @author wangyang
	 * @Title: unionScanCodeUnionReward
	 * @Description: 向联盟商转账
	 * @param
	 * @throws @return
	 * @date 2017-03-13 上午11:32:48
	 */
	private String unionScanCodeUnionReward(EnterpriseWalletIncomeExpendRecord producerWalletIncomeExpendRecord,
			WalletIncomeExpendRecord consumerWalletIncomeExpendRecord) throws ServiceException {
		try {
			Integer providerRefId = producerWalletIncomeExpendRecord.getProviderRefId(); // 联盟商id
			// Customer producerCustomer = new Customer(); // 联盟商会员

			BigDecimal payPrice = producerWalletIncomeExpendRecord.getInCome();
			BigDecimal allPrice = consumerWalletIncomeExpendRecord.getExPend();
			Integer customerId = consumerWalletIncomeExpendRecord.getCustomerId();
			logger.info("payPrice = " + payPrice);

			if (providerRefId != null && providerRefId != 0) {
				Integer count = 0;
				Customer producerCustomer = customerInterfaceImplDao.queryMemberCustomerById(customerId);
				EnterpriseWallet enterpriseWallet = enterpriseWalletInterfaceDao.queryWalletByCustomerId(providerRefId);
				Integer bindType = enterpriseWallet.getBindType();
				if (bindType - 1 == 0) {
					// 根据设置规则转账给联盟商会员获取营业额
					Map tParamMap = new HashMap();
					String payeeAccount = enterpriseWallet.getBankCodeNo(); // 捆绑收款支付宝账号
					String payeeRealName = enterpriseWallet.getBankBindUserName(); // 捆绑支付宝用户名
					tParamMap.put("payee_account", payeeAccount);
					tParamMap.put("payee_real_name", payeeRealName);
					tParamMap.put("payPrice", payPrice);
					tParamMap.put("remark", "转账给联盟商获取营业额货款");
					logger.info("payee_account===========" + payeeAccount);
					logger.info("payee_real_name===========" + payeeRealName);
					Map tResultMap = ALiTransfer.aliTransfer(tParamMap); // 转账结果
					String outBizNo = String.valueOf(JSONUtil
							.readValueToMap(JSONUtil.writeValueAsString(tResultMap.get("data"))).get("out_biz_no"));
					logger.info("out_biz_no = " + outBizNo); // 转账交易订单号
					tResultMap = ALiTransfer.validAliTransfer(outBizNo);
					if (tResultMap.get(Constant.STATUS).equals(Constant.STATUS_SUCCESS)) {
						count = 1;
					}
				} else {
					enterpriseWallet.setAccumulaCash(enterpriseWallet.getAccumulaCash().add(payPrice));
					enterpriseWallet.setRemainingCash(enterpriseWallet.getRemainingCash().add(payPrice));
					enterpriseWallet.setAccumulaTurnover(enterpriseWallet.getAccumulaTurnover().add(allPrice));
					count = enterpriseWalletInterfaceDao.updateWallet(enterpriseWallet);
				}

				if (count <= 0) { // 失败
					// 获取用户的设备号进行到账失败消息推送
					if (producerCustomer.getDeviceToken() != null && !producerCustomer.getDeviceToken().equals("")) {

						Integer deviceType = producerCustomer.getDeviceType();
						if (deviceType == 2) {
							// IOS推送
							String uMengAppKey = PropertiesUtils.getValue("UMENG_APP_KEY_IOS");
							String uMengAppSecret = PropertiesUtils.getValue("UMENG_APP_SECRET_IOS");
							Demo demo = new Demo(uMengAppKey, uMengAppSecret);
							demo.sendUnionTransferFailIOSUnicast(producerCustomer.getDeviceToken(),
									payPrice.toString());
						} else {
							// Android推送
							String uMengAppKey = PropertiesUtils.getValue("UMENG_APP_KEY_ANDROID");
							String uMengAppSecret = PropertiesUtils.getValue("UMENG_APP_SECRET_ANDROID");
							Demo demo = new Demo(uMengAppKey, uMengAppSecret);
							demo.sendUnionTransferFailAndroidUnicast(producerCustomer.getDeviceToken(),
									payPrice.toString());
						}
						logger.info(producerCustomer.getDeviceToken());
					}
					return "FAIL";
				}

				if (count > 0) { // 交易
					producerWalletIncomeExpendRecord.setStatus(1);
					enterpriseWalletIncomeExpendRecordInterfaceDao
							.updateWalletIncomeExpend(producerWalletIncomeExpendRecord);

					// 获取用户的设备号进行到账消息推送
					if (producerCustomer.getDeviceToken() != null && !producerCustomer.getDeviceToken().equals("")) {

						Integer deviceType = producerCustomer.getDeviceType();
						if (deviceType == 2) {
							// IOS推送
							String uMengAppKey = PropertiesUtils.getValue("UMENG_APP_KEY_IOS");
							String uMengAppSecret = PropertiesUtils.getValue("UMENG_APP_SECRET_IOS");
							Demo demo = new Demo(uMengAppKey, uMengAppSecret);
							demo.sendUnionIOSUnicast(producerCustomer.getDeviceToken(), payPrice.toString());
						} else {
							// Android推送
							String uMengAppKey = PropertiesUtils.getValue("UMENG_APP_KEY_ANDROID");
							String uMengAppSecret = PropertiesUtils.getValue("UMENG_APP_SECRET_ANDROID");
							Demo demo = new Demo(uMengAppKey, uMengAppSecret);
							demo.sendUnionAndroidUnicast(producerCustomer.getDeviceToken(), payPrice.toString());
						}
						logger.info(producerCustomer.getDeviceToken());
					}

					return "SUCCESS";
				}

			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return "FAIL";
	}

	/**
	 * @package com.sayimo.maker.user.service
	 * @author chenpy
	 * @Title: queryMemberMustReadList
	 * @Description: 查询会员必读列表
	 * @param
	 * @throws @return
	 * @date 2017-03-07 下午17:31:08
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Map queryMemberMustReadList(String mark) throws ServiceException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List list = customerInterfaceImplDao.getMemberMustReadList(mark);

			map.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			HashMap dataMap = Maps.newHashMap();
			dataMap.put("memberMustReadList", list);
			map.put(Constant.DATA, dataMap);
		} catch (DaoException de) {
			logger.error(de);
			throw new ServiceException(de);
		}
		return map;
	}

	/**
	 * @package com.sayimo.maker.user
	 * @author chenpy
	 * @Title:
	 * @Description:银星创客升级成为金星创客
	 * @param
	 * @throws @return
	 * @date 2017-02-20 上午11:37:30
	 */
	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
	public Map<String, Object> upgradeGoldMaker() throws ServiceException {

		Map<String, Object> resultMap = new HashMap<>();
		Map paramsMap = RequestUtils.bindRequestParam(request, HashMap.class);
		logger.info("paramMap = " + paramsMap);

		String[] requiredFields = { "payType", "customerId", "applyType" };
		if (!RequestUtils.checkRequireKV(paramsMap, requiredFields)) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}

		Integer payType = MapUtils.getInteger(paramsMap, "payType"); // 支付类型
		// 1微信支付；2支付宝支付
		String applyType = MapUtils.getString(paramsMap, "applyType");
		Double payPrice = 300D;
		// Double payPrice = 0.01D;

		String goodsName = "银星创客升级为金星创客", ordersNo = GeneratorUtils.generatorOrdersNo("006");

		Map<String, Object> payParamMap = new HashMap<>();
		payParamMap.put("goodsName", goodsName);
		payParamMap.put("ordersNo", ordersNo);
		payParamMap.put("payPrice", Double.valueOf(payPrice));

		payParamMap.put("_payPrice", Double.valueOf(payPrice));
		payParamMap.put("_ordersType", 5);
		payParamMap.put("_customerId", MapUtils.getInteger(paramsMap, "customerId"));

		logger.info("alipayParamMap = " + payParamMap);

		// 调用支付接口
		try {
			// 记录批次号
			String recordBatchCode = (new StringBuilder(String.valueOf(new Date().getTime()))
					.append(new RandomStringUtils().random(6, "0123456789"))).toString();
			// 收入支出记录（创客申请订单）
			Integer customerId = MapUtils.getInteger(paramsMap, "customerId");
			WalletIncomeExpendRecord expendRecord = new WalletIncomeExpendRecord();
			expendRecord.setEmsNo(ordersNo);
			String comment = "银星创客升级为金星创客";
			expendRecord.setCommet(comment);
			expendRecord.setCustomerId(customerId);
			expendRecord.setOrderType(4); // 创客
			expendRecord.setStatus(0);
			expendRecord.setFromType(payType == 1 ? 4 : 5);
			expendRecord.setExPend(new BigDecimal(payPrice));
			expendRecord.setRecordBatchCode(recordBatchCode);
			walletIncomeExpendRecordInterfaceDao.insertSelective(expendRecord);

			if (payType == 1) { // 微信支付
				if (applyType.equals("APP")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				} else if (applyType.equals("WEB")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				} else if (applyType.equals("PC")) {
					resultMap = WXScanCodePay.weixin_pay(payParamMap, request);
				} else if (applyType.equals("WAP")) {
					resultMap = WXPay.wxPayOrder(payParamMap, request);
				}

			} else { // 支付宝支付
				if (applyType.equals("APP")) {
					resultMap = ALiPay.aliPayOrder(payParamMap);
				} else if (applyType.equals("WAP")) {
					resultMap = AliWapPay.aliWapPayOrder(payParamMap);
				} else if (applyType.equals("PC")) {
					resultMap = AliScancodePay.creatOrCode(payParamMap);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * @package com.sayimo.maker.user
	 * @author chenpy
	 * @Title:
	 * @Description:升级金星申请回调
	 * @param
	 * @throws @return
	 * @date 2017-02-20 上午11:37:30
	 */
	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
	public synchronized Map<String, Object> upgradeGoldMakerCallback(Integer customerId, String tradeNo)
			throws ServiceException {

		Map<String, Object> resultMap = new HashMap<>();
		try {
			WalletIncomeExpendRecord walletIncomeExpendRecord = walletIncomeExpendRecordInterfaceDao
					.getWalletIncomeExpendByEmsNo(tradeNo);
			if (walletIncomeExpendRecord.getStatus() == 1) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				return resultMap;
			}

			Integer fromType = walletIncomeExpendRecord.getFromType();

			boolean isPaySuccess = false;
			if (fromType == 4) { // 微信支付
				isPaySuccess = WXPay.orderQuery(tradeNo);
			} else if (fromType == 5) { // 支付宝支付
				isPaySuccess = ALiPay.validAlipayTradeQuery(tradeNo);
			}

			if (isPaySuccess) { // 创客申请成功
				Customer customer = customerInterfaceImplDao.queryMemberCustomerById(customerId);
				customer.setMakerLevel(1); // 会员创客等级改为金星创客
				customerInterfaceImplDao.updateCustomer(customer);

				walletIncomeExpendRecord.setStatus(1);
				walletIncomeExpendRecordInterfaceDao.updateWalletIncomeExpend(walletIncomeExpendRecord);

				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				return resultMap;
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * @Package com.sayimo.maker.user.service.impl
	 * @Author 龚益君
	 * @MethodName:personalWalletBeToCash
	 * @Description:用户提现
	 * @param customerId
	 * @param payPrice
	 *            提现金额
	 * @return
	 * @throws ServiceException
	 * @throws DaoException
	 * @Date 2017年3月14日,下午4:09:29
	 */
	@Override
	public synchronized Map<String, Object> personalWalletBeToCash(Integer customerId, String _payPrice,
			String passWord) throws ServiceException {
		TransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = transactionManager.getTransaction(definition);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Wallet wallet = walletInterfaceImplService.queryWalletByCustomerId(customerId);
		if (!wallet.getPassWord().equals(passWord)) { // 钱包密码不正确
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.WALLET_PASSWORD_ERROR);
			return resultMap;
		} else {
			try {
				logger.info("_payPrice = " + _payPrice);
				BigDecimal payPrice = new BigDecimal(_payPrice);
				// 转账~

				BigDecimal num = wallet.getRemainingCash().subtract(payPrice);// 提现金额和钱包可提现金额对比
																				// 不能大于钱包可提现金额
				if (num.compareTo(new BigDecimal(0)) >= 0) {

					if (wallet.getBindType() == 1) {
						payPrice = payPrice.multiply(new BigDecimal(1 - 0.006));

						Map<String, Object> tParamMap = new HashMap<>();
						String payeeAccount = wallet.getBankCodeNo();
						String payeeRealName = wallet.getBankBindUserName();
						tParamMap.put("payee_account", payeeAccount);
						tParamMap.put("payee_real_name", payeeRealName);
						logger.info("payPrice =" + payPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
						tParamMap.put("payPrice", payPrice.setScale(2, BigDecimal.ROUND_HALF_UP)); // 四舍五入
						tParamMap.put("remark", "用户提现");
						Map tResultMap = ALiTransfer.aliTransfer(tParamMap); // 转账结果
						if (tResultMap.get(Constant.STATUS).equals(Constant.STATUS_ERROR)) { // 失败
							resultMap.put(Constant.STATUS, Constant.SYSTEM_ERROR);
							return resultMap;
						}
						String outBizNo = String.valueOf(JSONUtil
								.readValueToMap(JSONUtil.writeValueAsString(tResultMap.get("data"))).get("out_biz_no")); // 转账交易订单号
						logger.info("outBizNo = " + outBizNo);
						tResultMap = ALiTransfer.validAliTransfer(outBizNo);

						if (tResultMap.get(Constant.STATUS).equals(Constant.STATUS_SUCCESS)) { // 交易成功
							// 更新钱包信息
							wallet.setRemainingCash(num);

							walletInterfaceImplService.updateWallet(wallet);
							// 收入支出记录
							WalletIncomeExpendRecord incomeExpendRecord = new WalletIncomeExpendRecord();
							incomeExpendRecord.setRewardType(2); // 现金奖励
							incomeExpendRecord.setCustomerId(customerId);
							incomeExpendRecord.setExPend(payPrice.setScale(2, BigDecimal.ROUND_HALF_UP)); // 四舍五入
							incomeExpendRecord.setCommet("用户提现");
							incomeExpendRecord.setEmsNo(outBizNo);
							incomeExpendRecord.setFromType(5);
							incomeExpendRecord.setOrderType(7);
							incomeExpendRecord.setTransferStatus(3);
							walletIncomeExpendRecordServiceImpl.insertSelective(incomeExpendRecord);
						}
					} else if (wallet.getBindType() == 2) {

						// 更新钱包信息
						wallet.setRemainingCash(num);

						walletInterfaceImplService.updateWallet(wallet);
						// 收入支出记录
						WalletIncomeExpendRecord incomeExpendRecord = new WalletIncomeExpendRecord();
						incomeExpendRecord.setRewardType(2); // 现金奖励
						incomeExpendRecord.setCustomerId(customerId);
						incomeExpendRecord.setExPend(payPrice.setScale(2, BigDecimal.ROUND_HALF_UP)); // 四舍五入
						incomeExpendRecord.setCommet("用户提现");
						incomeExpendRecord.setEmsNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
						incomeExpendRecord.setFromType(1);
						incomeExpendRecord.setOrderType(7);
						incomeExpendRecord.setTransferStatus(1);
						walletIncomeExpendRecordServiceImpl.insertSelective(incomeExpendRecord);
					}
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				} else {
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					resultMap.put(Constant.ERROR_CODE, Constant.WALLET_MONEY_NOT_ENOUGH);
				}
				transactionManager.commit(status);
				return resultMap;
			} catch (Exception e) {
				logger.error(e);
				e.printStackTrace();
				transactionManager.rollback(status);
				throw new ServiceException(e);
			}

		}
	}

	/**
	 * @Package com.sayimo.maker.user.service
	 * @Author 龚益君
	 * @MethodName:updateEnterpriseWalletInfo
	 * @Description:修改企业钱包绑定银行信息
	 * @param customerId
	 * @param wallet
	 * @return
	 * @throws ServiceException
	 * @Date 2017年4月17日,上午11:25:59
	 */
	public Map<String, Object> updateEnterpriseWalletInfo(EnterpriseWallet wallet) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// update钱包信息
			Integer count = enterpriseWalletInterfaceDao.updateWallet(wallet);
			if (count > 0) {
				Map<String, Object> map = new HashMap<>();
				map.put(Constant.MSG, "修改成功");
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, map);
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_ERROR);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/**
	 * @Package com.sayimo.maker.user.service.impl
	 * @Author 龚益君
	 * @MethodName:queryEnterpriseWalletInfo
	 * @Description:获取钱包信息
	 * @param customerId
	 * @return
	 * @throws ServiceException
	 * @Date 2017年4月17日,下午2:32:18
	 */
	public Map<String, Object> queryEnterpriseWalletInfo(Integer customerId) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 获取操作用户
			Customer customer = customerInterfaceImplDao.queryMemberCustomerById(customerId);
			EnterpriseWallet wallet = enterpriseWalletInterfaceDao.queryWalletByCustomerId(customer.getProviderRefId());
			if (wallet != null && wallet.getId() > 0) {
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, wallet);
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_NO_DATA);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return resultMap;
	}
	 /**
	 * @Package com.sayimo.maker.user.service.impl
	 * @Author 龚益君
	 * @MethodName:queryAllBankBranch
	 * @Description:获取所有支行信息
	 * @param code
	 * @param bankCode
	 * @return
	 * @throws ServiceException
	 * @Date 2017年4月17日,下午4:01:12
	 */
	public Map<String, Object> queryAllBankBranch(String code, String bankCode) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<Object> bankBranchs = enterpriseWalletInterfaceDao.queryAllBankBranch(code, bankCode);
			if (bankBranchs != null && bankBranchs.size() > 0) {
				Map<String, Object> data = new HashMap<>();
				data.put("bankBranchList", bankBranchs);
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, data);
			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_NO_DATA);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			throw new ServiceException(e);
		}
		return resultMap;
	}
}
